package utils

import (
	"context"
	"errors"
	"github.com/beego/beego/v2/client/cache"
	_ "github.com/beego/beego/v2/client/cache/redis"
	"github.com/beego/beego/v2/core/logs"
	"github.com/spf13/viper"
	"time"
)

var C *Cache

func InitCache() {
	enable := viper.GetBool("cache.enable")
	if enable {
		cacheConn := viper.GetString("cache.dsn")
		cacheType := viper.GetString("cache.type")
		c := NewCache(cacheType, cacheConn)
		C = &c
	}
}

type Cache struct {
	beegoCache cache.Cache
}

// NewCache 实例化
func NewCache(cacheType string, cacheConn string) Cache {
	_cache, err := cache.NewCache(cacheType, cacheConn)
	if err != nil {
		logs.Error("cache init err: %s", err)
	}
	return Cache{
		beegoCache: _cache,
	}
}

// GetCache 返回缓存句柄
func (__ *Cache) getCache() cache.Cache {
	return __.beegoCache
}

// CGet 获取缓存信息，如果不存在返回空字符串
func CGet(key string) (string, error) { return C.CGet(key) }
func (__ *Cache) CGet(key string) (string, error) {
	value, err := __.getCache().Get(context.Background(), key)
	if err != nil {
		return "", err
	}
	if value == nil {
		return "", errors.New("value is empty")
	}
	switch value.(type) {
	case []byte:
		return string(value.([]byte)), nil
	case string:
		return value.(string), nil
	default:
		return "", nil
	}
}

// CPut 更新缓存信息，如果不存在返回空字符串
func CPut(key, value string, expireSecond int64) error { return C.CPut(key, value, expireSecond) }
func (__ *Cache) CPut(key, value string, expireSecond int64) error {
	err := __.getCache().Put(context.Background(), key, value, time.Duration(expireSecond)*time.Second)
	return err
}

// CDel 删除缓存信息
func CDel(key string) error { return C.CDel(key) }
func (__ *Cache) CDel(key string) error {
	err := __.getCache().Delete(context.Background(), key)
	return err
}
